﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace CCF20Model
{
    public class CustomerCollection : ObservableCollection<CustomerData>
    {
        private CCF20Entities ccf20Entities;
        private string GetLastCustomerNo()
        {
            Customer lastCustomer = ccf20Entities.Customers.OrderByDescending(c => c.CustomerID).FirstOrDefault();
            if (lastCustomer != null)
            {
                int temp;
                if (int.TryParse(lastCustomer.CustomerNo, out temp))
                {
                    return (temp + 1).ToString();
                }
                else
                {
                    return string.Concat(lastCustomer.CustomerNo, "1");
                }
            }
            else
            {
                return null;
            }
        }

        protected override void InsertItem(int index, CustomerData item)
        {
            item.MyDevice = new Device();
            item.IsReadOnly = false;
            ccf20Entities.Devices.AddObject(item.MyDevice);
            item.MyVehicle = new Vehicle();
            ccf20Entities.Vehicles.AddObject(item.MyVehicle);
            item.MyVehicle.VehicleTypeID = 0;
            item.MyCustomer = new Customer();
            ccf20Entities.Customers.AddObject(item.MyCustomer);
            item.MyCustomer.SN = string.Empty;
            item.MyCustomer.SNPwd = string.Empty;
            item.MyCustomer.IDS = string.Empty;
            item.MyCustomer.Name = string.Empty;
            item.MyCustomer.FirstMobile = string.Empty;

            item.MyDevice.Customer = item.MyCustomer;
            item.MyVehicle.Customer = item.MyCustomer;
            item.MyDevice.Vehicle = item.MyVehicle;
            item.MyCustomer.CustomerNo = GetLastCustomerNo();
            item.MyCustomer.isNewCustomer = true;
            base.InsertItem(index, item);
            //ccf20Entities.SaveChanges();
        }

        protected override void RemoveItem(int index)
        {

            Customer currentCustomer = ((CustomerData)this[index]).MyCustomer;
            if (currentCustomer.CustomerID > 0)
            {
                ccf20Entities.SafeDelete(currentCustomer.Devices.FirstOrDefault());
                ccf20Entities.SafeDelete(currentCustomer.TransferedCustomers.FirstOrDefault());
                ccf20Entities.SafeDelete(currentCustomer.Vehicles.FirstOrDefault());
                ccf20Entities.SafeDelete(currentCustomer.Devices.FirstOrDefault());
                ccf20Entities.SafeDelete(currentCustomer);
                ccf20Entities.SaveChanges();
            }
            base.RemoveItem(index);

        }
        public CustomerCollection(IEnumerable<CustomerData> customers, CCF20Entities context)
            : base(customers)
        {
            ccf20Entities = context;
        }

    }
}
